package com.sinba.itsm;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyFilter implements Filter{

	
	
	public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException{
//		try{
//			HttpServletRequest req = (HttpServletRequest) request;
//			
//			String url = req.getRequestURI(  );
//			if(url!=null && url.indexOf("pages/")!=-1){
//				chain.doFilter( request, response );
//			}else{
//				if()
//			}
//		}catch ( Exception ex ){
//            ex.printStackTrace();
//        }
		
		HttpServletRequest servletrequest = (HttpServletRequest) request;
	    HttpServletResponse servletresponse = (HttpServletResponse) response;
	    String url = servletrequest.getRequestURI(  );
	    if(url!=null && url.indexOf("admin/")!=-1){
			chain.doFilter( request, response );
		}else{
			String param = "";
		    String paramValue = "";
		     //设置请求编码格式
		     servletresponse.setContentType("text/html");
		     servletresponse.setCharacterEncoding("UTF-8");
		     servletrequest.setCharacterEncoding("UTF-8");
		     java.util.Enumeration params = request.getParameterNames();
		     boolean result = true;
		     //循环读取参数
		     while (params.hasMoreElements()){
		    	 param = (String) params.nextElement(); //获取请求中的参数
		    	 String[] values = servletrequest.getParameterValues(param);//获得每个参数对应的值
		    	 for (int i = 0; i < values.length; i++) {
			         paramValue = values[i];
			         if(paramValue.indexOf("script")!=-1 || paramValue.indexOf("SCRIPT")!=-1){
			        	 result = false;
			        	 break;
			         }
			         //转换目标字符变成对象字符，可以多个。后期扩展特殊字符库用于管理
			         paramValue = paramValue.replaceAll("'",""); 
			         //paramValue = paramValue.replaceAll("@","");//邮件地址提交时，删除了@字符
			         paramValue = paramValue.replaceAll("胡锦涛","***");
			         //这里还可以增加，如领导人 自动转义成****,可以从数据库中读取非法关键字。
			         values[i] = paramValue;
		    	 }
		 
		       //把转义后的参数重新放回request中
		       request.setAttribute(param, paramValue);
		     }
		     if(result){
		    	//继续向下 执行请求，如果有其他过滤器则执行过滤器
			    chain.doFilter(request, response);
		     }
		      
		}
	}
	
	
	public void init(FilterConfig fConfig) throws ServletException{}
	
	public void destroy(){
    }
}
